<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import {fetchAddCheckItem, fetchEditCheckItem, fetchGetAllArea,fetchGetAllCategory,fetchGetAllAreaList} from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'ItemOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.CheckItem | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.check.item.addItem'),
    edit: $t('page.check.item.editItem')
  };
  return titles[props.operateType];
});

// type Model = Pick<
//   Api.SystemManage.User,
//   'userName' | 'userGender' | 'nickName' | 'userPhone' | 'userEmail' | 'userRoles' | 'status'
// >;
type Model = Pick<
  Api.SystemManage.CheckItem, 'id' | 'areaId'  |  'name' | 'remark' | 'categoryId' | 'standard' | 'score' | 'scoringMethod' | 'deficiencyScore' | 'isusing'
>;
const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    remark: 'test-remark',
    areaId: '1',
    categoryId: '1',
    name: 'test-name',
    standard: 'test-standard',
    score: 0,
    scoringMethod: 'test-scoringMethod',
    deficiencyScore: 0,
    isusing: 1
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'isusing'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  isusing: defaultRequiredRule
};

const CategoryOptions = ref<CommonType.Option<string>[]>([]);
const AreaOptions = ref<CommonType.Option<string>[]>([]);
const AreaNewOptions = ref();
async function getCategoryOptions() {
  const { error, data } = await fetchGetAllCategory();
  if (!error) {
    const options = data.map(item => ({
      label: item.name,
      value: item.id
    }));
    CategoryOptions.value = [...options];
  }
}
async function getAreaOptions() {
  const { error, data } = await fetchGetAllArea();
  if (!error) {
    const options = data.map(item => ({
      label: item.name,
      value: item.id
    }));
    AreaOptions.value = [...options];
  }
}
async function getAreaNewOptions() {
  const { error, data } = await fetchGetAllAreaList();
  if (!error) {
    console.log(data)
   const options =  transformToOptions(data)
   console.log(options)
    AreaNewOptions.value = options;
  }
}


function transformToOptions(data) {
  return Object.keys(data).map(key => {
    return {
      label: key,
      key: key,
      children: data[key].map(item => ({
        label: item.name,
        key: item.id,
        category_id:item.category_id
      }))
    };
  });
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(props.rowData);
  try {
    // 验证表单
    await validate();
    // 根据操作类型构造请求参数
    const params = {
      ...model.value
    };// 深拷贝，避免直接修改 model.value
    let response;
    const { id, ...restParams } = params;
    // 根据操作类型调用不同的接口
    switch (props.operateType) {
      case 'add':
        // 调用添加接口
        console.log(params);
        response = await fetchAddCheckItem(restParams);
        break;
      case 'edit':
        console.log(params);
        response = await fetchEditCheckItem(params);
        break;
      default:
        throw new Error('未知的操作类型');
    }
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.updateSuccess'));
    // 关闭抽屉
    closeDrawer();
    // 触发父组件的事件，通知更新表格数据
    emit('submitted');
  } catch (error) {
    // 捕获可能的错误
    console.error('Submit Error:', error);
    // 根据错误类型显示不同的提示
    const errorMessage = $t('common.operationFailed');
    window.$message?.error(errorMessage);
  }
}
function handleUpdateValue(
        value,
        option
      ) {
        model.value.categoryId = option.category_id
        model.value.areaId = option.key
        console.log(model.value)
      }
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getCategoryOptions();
    getAreaOptions();
    getAreaNewOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>

      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="类别-区域">
          <n-tree-select
              :show-path="true"
              :options="AreaNewOptions"
              @update:value="handleUpdateValue"
            />
        </NFormItem>

        <NFormItem :label="$t('page.check.item.name')">
          <NInput v-model:value="model.name" :placeholder="$t('page.check.item.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.standard')">
          <NInput v-model:value="model.standard" :placeholder="$t('page.check.item.form.standard')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.score')">
          <NInput v-model:value="model.score" :placeholder="$t('page.check.item.form.score')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.scoringMethod')">
          <NInput v-model:value="model.scoringMethod" :placeholder="$t('page.check.item.form.scoringMethod')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.deficiencyScore')">
          <NInput v-model:value="model.deficiencyScore" :placeholder="$t('page.check.item.form.deficiencyScore')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.remark')">
          <NInput v-model:value="model.remark" :placeholder="$t('page.check.item.form.remark')" />
        </NFormItem>
        <NFormItem :label="$t('page.check.item.isusing')">
          <NRadioGroup v-model:value="model.isusing">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
